#include "sgp30.h"
#include "delay.h"
extern i2c_t *i2c;
static u32 Co2Data, TVOCData; // 定义CO2浓度变量与TVOC浓度变量
static void sgp30_write(u8 cmd_h, u8 cmd_l)
{
    // start();
    // sendByte(SGP30_ADDRESS << 1 | WRITE);
    // waitAck();
    // sendByte(cmd_h);
    // waitAck();
    // sendByte(cmd_l);
    // waitAck();
    // stop();
    i2c->Pi2cStart();
    i2c->Pi2cSendByte(SGP30_ADDRESS << 1 | WRITE);
    i2c->Pi2cWaitAck();
    i2c->Pi2cSendByte(cmd_h);
    i2c->Pi2cWaitAck();
    i2c->Pi2cSendByte(cmd_l);
    i2c->Pi2cWaitAck();
    i2c->Pi2cStop();
    Delay_s(1);
}

void sgp30_init(void)
{
    sgp30_write(CMD_HINGH, INIT_AIR_QUALITY);
    Delay_ms(1000);
}

static void sgp30_read_result(void)
{
    u32 data;
    u8 crc;

    i2c->Pi2cStart();
    i2c->Pi2cSendByte(SGP30_ADDRESS << 1 | READ);
    if (i2c->Pi2cWaitAck() == 0)
    {
        data = i2c->Pi2cReciveByte(1);
        data <<= 8;
        data += i2c->Pi2cReciveByte(1);
        crc = i2c->Pi2cReciveByte(1); // crc数据舍弃
        crc = crc;
        data <<= 8;
        data += i2c->Pi2cReciveByte(1);
        data <<= 8;
        data += i2c->Pi2cReciveByte(0);
        i2c->Pi2cStop();
    }
    Co2Data = (data & 0xffff0000) >> 16;
    TVOCData = (data & 0x0000ffff);
}

void sgp30_end_init(void)
{
    sgp30_write(CMD_HINGH, MEASURE_AIR_QUALITY);
    sgp30_read_result();
    while (Co2Data == 400 && TVOCData == 0)
    {
        sgp30_write(CMD_HINGH, MEASURE_AIR_QUALITY);
        sgp30_read_result();
        DBG("now checking....\r\n");
        Delay_ms(100);
    }
}

static void sgp30_write_fast(u8 cmd_h, u8 cmd_l)
{
    i2c->Pi2cStart();
    i2c->Pi2cSendByte(SGP30_ADDRESS << 1 | WRITE);
    i2c->Pi2cWaitAck();
    i2c->Pi2cSendByte(cmd_h);
    i2c->Pi2cWaitAck();
    i2c->Pi2cSendByte(cmd_l);
    i2c->Pi2cWaitAck();
    i2c->Pi2cStop();
    Delay_ms(100);
}
void sgp30_get_value(u32 *co2, u32 *tvoc)
{
    sgp30_write_fast(CMD_HINGH, MEASURE_AIR_QUALITY);

    sgp30_read_result();
    *co2 = Co2Data;
    *tvoc = TVOCData;
    // DBG("co2:%dppm,TVOC:%dppd\r\n", Co2Data, TVOCData);
    Co2Data = 0;
    TVOCData = 0;
    // Delay_ms(1000);
}

sgp30_t *sgp30Create(void)
{
    static sgp30_t sgp30;
    sgp30.Psgp30Init=sgp30_init;
    sgp30.Psgp30GetValue=sgp30_get_value;
    sgp30.Psgp30EndInit=sgp30_end_init;
    return &sgp30;
}
